/**
 * 节流函数
 * @param fn 将要处理的函数
 * @param wait 时间, 单位为毫秒
 * @returns 包装好的节流函数
 */
export default function throttle<T extends any[], N>(fn: (...args: T) => N, wait: number = 300): (...args: T) => void {
  let timeId = null as any;
  return function (this: any, ...args: any[]) {
    if (timeId) return;
    timeId = setTimeout(() => {
      fn.apply(this, args as T);
      clearTimeout(timeId);
      timeId = null;
    }, wait);
  };
}

/**
 * 生成唯一ID，保证返回指定长度
 * @param length 长度（默认 16）
 * @returns 唯一ID
 */
export function generateUniqueId(length: number = 16): string {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let result = "";
  const randomValues = new Uint8Array(length);
  crypto.getRandomValues(randomValues);

  for (let i = 0; i < length; i++) {
    result += chars[randomValues[i] % chars.length];
  }

  return result;
}
